using System;
using System.IO;
using System.Text;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

using RealDolmen.Controls;
using RealDolmen.SharePoint.ListFeatures.Elements;
using RealDolmen.Helpers;

[assembly: WebResource("RealDolmen.SharePoint.ListFeatures.Resources.Form.ScriptLib.js", "application/x-javascript")]
namespace RealDolmen.SharePoint.ListFeatures.Controls
{
    public class ListFeatureFormMenuItem : ListFeatureMenuItem
    {
        #region Properties
        private string location;
        public override string Location
        {
            get
            {
                if (string.IsNullOrEmpty(location))
                {
                    SPControlMode controlMode = SPContext.Current.FormContext.FormMode;

                    switch (controlMode)
                    {
                        case SPControlMode.Edit:
                            location = "EditFormToolbar";
                            break;

                        case SPControlMode.New:
                            location = "NewFormToolbar";
                            break;

                        default:
                            location = "DisplayFormToolbar";
                            break;
                    }
                }
                return location;
            }
        }

        public ToolBar ToolBar
        {
            get
            {
                return Menu as ToolBar;
            }
        }
        #endregion // Properties

        #region AddControl
        private StringBuilder stringBuilder;
        private string currentToolBarId = string.Empty;

        protected override void BeforeAddControls()
        {
            Control toolBar = ControlHelper.GetClosestParent<ToolBar>(this);
            currentToolBarId = toolBar.ClientID;
            stringBuilder = new StringBuilder();

            ClientScriptManager cs = Page.ClientScript;

            // Add the library if necessary
            if (!cs.IsClientScriptBlockRegistered(GetType(), "LF.Form.ScriptLib"))
            {
                /*
                string script = cs.GetWebResourceUrl(GetType(), "RealDolmen.SharePoint.ListFeatures.Resources.Form.ScriptLib.js");
                script = string.Format("<script type=\"text/javascript\" src=\"{0}\"></script>\n", script);
                */
                // using WebResource.axd gives slow performance for some reason, so including it directly in page
                string script = RealDolmen.Helpers.Helper.GetAssemblyResource("RealDolmen.SharePoint.ListFeatures.Resources.Form.ScriptLib.js", System.Reflection.Assembly.GetExecutingAssembly());
                script = string.Format("<script type=\"text/javascript\">{0}</script>\n", script);

                cs.RegisterStartupScript(
                   GetType(), "LF.Form.ScriptLib",
                   script, false);
            }
        }
        protected override void AddControl(Control control, int index, ListFeatureCustomActionElement customAction)
        {
            if (control != null)
            {
                // This separator will come after the item
                if (true)
                {
                    CreateJsSeparator(index);
                }

                CreateJsButton(control, index);

                // This separator will come before the item
                if (index > 0)
                {
                    CreateJsSeparator(index);
                }
            }
        }

        #region Core Javascript
        private void CreateJsSeparator(int nextIndex)
        {
            stringBuilder.AppendLine("addFormSeparator(");
            stringBuilder.AppendFormat("       '{0}', {1});\n", currentToolBarId, nextIndex);
        }

        private void CreateJsButton(Control control, int nextIndex)
        {
            StringBuilder sbControl = new StringBuilder();
            HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sbControl));
            control.RenderControl(writer);
            //System.Diagnostics.Debugger.Break();
            string strControl = JavascriptHelper.EscapeChar(sbControl.ToString(), '\'');

            stringBuilder.AppendLine("addFormItem(");
            stringBuilder.AppendFormat("       '{0}',\n", strControl);
            stringBuilder.AppendFormat("       '{0}', {1});\n", currentToolBarId, nextIndex);
        }
        #endregion // Core Javascript 

        protected override void AfterAddControls()
        {
            string output = stringBuilder.ToString();

            if (output.Length > 8)
            {
                Page.ClientScript.RegisterStartupScript(
                   GetType(),
                   Guid.NewGuid().ToString(),
                   output, true);
            }
        }

        #endregion // AddControl

        #region BuildControl
        protected override Control BuildControl(ListFeatureCustomActionElement customAction)
        {
            FormButton fb = null;
            if (DoesListItemComplyToRegistration(customAction))
            {
                //System.Diagnostics.Debugger.Break();
                fb = new FormButton();
                fb.Text = customAction.ParsedTitle;

                if (customAction.ImageUrl != null)
                    fb.ImageUrl = customAction.ImageUrl;
                //fb.AccessKey = element.AccessKey;
                if (customAction.Url != null)
                    fb.NavigateUrl = customAction.ParsedUrl;

                if (customAction.Rights != null)
                {
                    fb.PermissionsString = customAction.Rights;
                    fb.PermissionMode = PermissionMode.Any;
                    fb.PermissionContext = PermissionContext.CurrentItem;
                }
            }
            return fb;
        }

        private static bool DoesListItemComplyToRegistration(ListFeatureCustomActionElement customAction)
        {
            SPListItem listItem = SPContext.Current.ListItem;
            bool comply = true;
            if (listItem != null)
            {
                if (!string.IsNullOrEmpty(customAction.RegistrationType) && !string.IsNullOrEmpty(customAction.RegistrationId))
                {
                    if (customAction.RegistrationType == "ContentType")
                    {
                        comply = listItem.ContentType.Id.ToString().StartsWith(customAction.RegistrationId);
                    }
                    else if (customAction.RegistrationType == "List")
                    {
                        comply = listItem.ParentList.BaseTemplate.ToString() == customAction.RegistrationId;
                    }
                    else if (customAction.RegistrationType == "FileType")
                    {
                        comply = false;
                        string ext = listItem.Url;
                        int idx = ext.LastIndexOf('.');
                        if (idx > 0)
                        {
                            ext = ext.Substring(idx + 1).ToLower();
                            comply = ext == customAction.RegistrationId.ToLower();
                        }
                    }
                    else if (customAction.RegistrationType == "ProgId")
                    {
                        comply = false;
                        if (listItem.File != null)
                        {
                            comply = listItem.File.ProgID == customAction.RegistrationId;
                        }
                    }
                }
            }
            return comply;
        }
        #endregion // BuildControl
    }
}